﻿using System.Collections.Generic;
using System.Linq;
using Dolany.UtilityTool;
using JetBrains.Annotations;
using Missbot.Core.Base;
using Missbot.Core.Cache;
using Missbot.Model.MsgCmds.Messaging;
using Missbot.Model.MsgInfos;
using Newtonsoft.Json;

namespace Missbot.Core.Channels
{
    [UsedImplicitly]
    public class MessagingChannel : IMsgChannel
    {
        public override string Name => "messaging";
        public override ChannelType BindingType => ChannelType.Messaging;
        public override string ChannelFlag => "message";

        protected override void Send(OutboxDTO dto)
        {
            var cmd = dto.FileIDs.IsNullOrEmpty()
                          ? new CreateGroupMessageCmd
                          {
                              GroupID = dto.Group.ID,
                              Text = dto.User == null ? dto.Text : $"@{dto.User.UserName} {dto.Text}"
                          }
                          : new CreateGroupMsgWithFileCmd
                          {
                              GroupID = dto.Group.ID,
                              Text = dto.User == null ? dto.Text : $"@{dto.User.UserName} {dto.Text}",
                              FileID = dto.FileIDs.First()
                          };

            MsgSender.PushMsg(cmd);
        }

        public override void SendGroup(IEnumerable<InstanceUser> Users, InstanceGroup Group, string SourceID, string text, string file = null)
        {
            Send(new InboxSession { Group = Group, SourceID = SourceID }, text, file);
        }

        protected override InboxSession ParseDataImpl(string msg)
        {
            var model = JsonConvert.DeserializeObject<MessagingInfo>(msg);
            if (model?.Body == null)
            {
                return null;
            }

            var body = model.Body.Body;
            return new InboxSession
            {
                Group = body.Group,
                User = body.User,
                Text = body.Text,
                Files = new[] { body.File },
                Channel = this,
                SourceID = body.ID
            };
        }
    }
}